// pages/gatherHouse/scanAddHouse/scanAddHouse.js
import p from "../../../utils/platform";
import api from "../../../common/api";
import { moveHouseLog } from "../../../common/log";
import constant from "../../../common/constant";
import * as transferData from "../../../models/transferData";
import { menuHandler } from "../../../common/menuHandler";
import { HOUSE_MOVE } from "../../../common/menuId";
import { pollingModeRequest } from "../../../utils/utilsNew";
const computedBehavior = require("miniprogram-computed");

var app = getApp();
const URL_MAP = ["58.com", "ke.com", "lianjia.com", "anjuke.com"];

const MOVE_ERROR_TIPS = {
  20003: '目前不支持该网站搬家，请试试其他链接。',
  20004: '该房源已存在',
  601: '房源搬家超时，请稍后再试',
  606: '操作失败，请稍后再试',
  201: 'vr预计5分钟后下载完成'
};

let clearTimer = null;
Page({
  behaviors: [computedBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    subscribe: false,
    isLoadHouseDone: false, //加载房源完成
    isLoadingShow: false, //加载房源中
    list: [
      {
        name: "居客网",
        title: "“居客网”网站房源详情页右下方“手机看房源”即是房源二维码",
        img: "https://api.shulanfd.com/aist-filesvr-web/api/files/1689db218d264ca6ad8e25e86f19ad39",
      },
      {
        name: "真房源网",
        title: "“真房源网”网站房源详情页点击“分享此房源”即是弹框二维码",
        img: "https://api.shulanfd.com/aist-filesvr-web/api/files/73e6c9fdf88745f98cd704c8fe5c91dd",
      }, //贝壳
      // { name: "链家", title: "“链家”网站房源详情页点击“分享此房源”即是弹框二维码", img: "https://api.shulanfd.com/aist-filesvr-web/api/files/bc150250efce49a7a84a26c4ab527c64" },
      {
        name: "同城网",
        title: "“58同城网”网站房源详情页右下方“手机看房源”即是房源二维码",
        img: "https://api.shulanfd.com/aist-filesvr-web/api/files/a14bf63ca51a4c2fa6321931ee061325",
      },
    ],
    siteNumber: 0, //网站
    helpGuide: false,
    kefu: false,
    height: 0, //导航栏的高度
    moveHouseFailed: false, // 房源搬家失败提示方式   1失败 2可重试
    back: false, // 右上角导航栏是否为返回
    isTips: true, //是否提示
    haveMoveHouse: false, //  是否成功扫码搬家过
    hold: false, //挽留 1、没有任何操作；2、没有扫任何码；3、扫码失败
    errorMsgText: '',
  },

  computed: {
    titlesName(data) {
      return data.list.map((v) => v.name).join("、");
    },
  },

  /**
   * 生命周期函数--监听页面加载
   * options
   *    skipMenu 跳过权限校验
   */
  onLoad: function (options) {
    // options.scanCode='https://m.ke.com/cwap/guide/hsdetail?cityId=310000&hsId=107102790717';
    // options.subscribe=true;
    if (options.subscribe) {
      this.setData({
        subscribe: true,
      });
    }
    app.globalData.loginPromise.then(() => {
      this.getNavHeight();
      this.queryPmReferenceDetailInfoByRefCode();
      moveHouseLog({ logType: "0" });

      if (options.scanCode) {
        let scanCode = decodeURIComponent(options.scanCode);
        console.log("scanCode", scanCode);
        this.setData({
          result: scanCode,
        });

        if (options.skipMenu) {
          this.handleScanCode(scanCode);

        } else {
          menuHandler.call(this, HOUSE_MOVE).then(() => {
            this.handleScanCode(scanCode);
          }).catch((errorPromise) => {
            if (errorPromise && errorPromise.then) {
              errorPromise.then(() => {
                if (this.data.subscribe) {
                  wx.navigateBack()
                }
              })
            }
          });
        }
      }
      if (!app.globalData.haveMoveHouse) {
        app.globalData.hold = 1;
      } else {
        this.setData({
          back: true,
        });
      }
    });
  },

  handleScan() {
    if (!app.globalData.haveMoveHouse) {
      app
        .mobileLogin(null, "房源搬家")
        .then(() => {
          app.globalData.hold = 2;
        })
        .catch(() => {
          if (app.globalData.afterMobileAuthorCallBack == null) {
            app.globalData.afterMobileAuthorCallBack = () => {
              p.redirectTo({ url: "/pages/gatherHouse/scanAddHouse/scanAddHouse" });
            };
          } else {
            app.globalData.afterMobileAuthorCallBack = null;
            app.globalData.afterMobileAuthorCallBack = () => {
              p.redirectTo({ url: "/pages/gatherHouse/scanAddHouse/scanAddHouse" });
            };
          }
        });
    }

    this.setData({
      moveHouseFailed: false,
    });

    app
      .mobileLogin(null, "房源搬家")
      .then(() => {
        // 正式扫码前校验权限
        menuHandler.call(this, HOUSE_MOVE).then(() => {
          wx.scanCode({
            success: (res) => {
              console.log("扫码===", res.result);
              const result = res.result;
              this.setData({
                result,
              });
              this.handleScanCode(result);
            },

            fail: (res) => {},
          });
        })
        .catch(() => {})
        ;
      })
      .catch(() => {
        app.globalData.afterMobileAuthorCallBack = () => {
          wx.redirectTo({ url: "/pages/gatherHouse/scanAddHouse/scanAddHouse" });
        };
      });
  },

  /**
   * 
   * @param {*} sourceUrl 扫码路径
   * @param {*} skipRepeat 0 默认值 校验重复房源、1 跳过重复房源校验
   * @returns 
   */
  handleScanCode(sourceUrl, skipRepeat = 0) {
    console.log("扫码路径sourceUrl", sourceUrl);
    let bool = URL_MAP.find((item) => {
      return sourceUrl.indexOf(item) > -1;
    });

    if (!bool || sourceUrl.indexOf("communitydetail") !== -1) {
      if (!app.globalData.haveMoveHouse) {
        app.globalData.hold = 3;
      }
      p.showModal({
        content: `目前只支持${this.data.titlesName}二手房和出租房的二维码,请查看教程二维码位置`,
        showCancel: false,
      });

      return;
    }

    moveHouseLog({
      logType: "1",
      sourcePickOutHouse: sourceUrl,
    });

    // 首次请求
    api.movingHouse([{ url: sourceUrl, skipRepeat }], ({ data }) => {
      if (!data.isSuccess || !data.content) {
        // 失败场景
        p.showToast({ title: data.errorMessage || '系统异常！', icon: "none" });
        return;
      }

      // 使用搬家次数
      api.getMemberPower({ menuId: HOUSE_MOVE }, (res) => {});

      // 搬家加载中...
      this.setData({ isLoadingShow: true });

      let id = data.content[0].id;
      // 成功继续向下 轮询
      let ajaxFn = api.taskListByIds.bind(null, [id]);
      clearTimer && clearTimer();
      clearTimer = pollingModeRequest(ajaxFn, ({ data }) => {
        const info = data.content[0];
        
        if (!app.globalData.haveMoveHouse) {
          app.globalData.hold = 3;
        }

        // 接口失败
        if (!data.isSuccess) {
          this.setData({ isLoadingShow: false });
          p.showToast({ title: data.errorMessage || '系统异常！', icon: "none" });
          this._log(sourceUrl, false, data.errorMessage);
          return false;
        }

        // 搬家完成
        if (info.pickOutStatus == "S") {
          if (this.data.subscribe) {
            transferData.setData("isRefreshSubscribe", true);
          }
          if (!app.globalData.haveMoveHouse) {
            app.globalData.hold = false;
          }

          this.data.houDelId = info.delId;
          this.setData({ isLoadHouseDone: true });

          this._log(sourceUrl, true, info.delId);

          // 搬家失败
        } else if (info.pickOutStatus == "F") {
          this.setData({ isLoadingShow: false });
          
          // 重复搬家
          if (info.errorCode == '20004') {
            this.setData({
              moveHouseFailed: 2,
              houDelId: info.delId,
            });
            
          } else {
            this.setData({
              moveHouseFailed: 1,
              errorMsgText: MOVE_ERROR_TIPS[info.errorCode] || '哎~房源搬家失败了'
            });
          }
          this._log(sourceUrl, false, info.errorMessage);
        }
        
        return info.pickOutStatus !== "S" && info.pickOutStatus !== "F";
      }, 2500, false);
    });
  },

  _log(sourceUrl, isSuccess, idMsg) {
    let logObj = {
      logType: "2",
      sourcePickOutHouse: sourceUrl,
      create_result: isSuccess ? "0" : "1",
    };
    if (isSuccess) {
      logObj.del_id = idMsg || "";
    } else {
      logObj.response = idMsg || "";
    }

    moveHouseLog(logObj);
  },

  handleLoadHouseDone() {
    this.setData({
      isLoadingShow: false,
      isLoadHouseDone: false,
    });

    setTimeout(() => {
      if (this.data.houDelId) {
        if (this.data.subscribe) {
          p.redirectTo({
            url: `/pages/addHouse/infoEntryHouse/infoEntryHouse?houDelId=${this.data.houDelId}&isScan=true&subscribe=true`,
          });
        } else {
          p.navigateTo({
            url: `/pages/addHouse/infoEntryHouse/infoEntryHouse?houDelId=${this.data.houDelId}&isScan=true`,
          });
        }
      }
    }, 500);
  },

  timeoutFn() {
    this.setData({
      isLoadingShow: false,
    });
    p.showToast({
      title: "录房超时！",
      icon: "none",
    });
  },

  chooseSite(e) {
    console.log(e);
    this.setData({
      siteNumber: e.target.dataset.number,
    });
  },
  // 打开引导
  openHelp() {
    this.setData({
      helpGuide: true,
    });
  },
  // 关闭引导
  closeHelp() {
    this.setData({
      helpGuide: false,
      moveHouseFailed: false,
    });
  },
  closeHold(e) {
    this.setData({
      helpGuide: false,
      moveHouseFailed: false,
      // hold: false,
      isTips: false,
    });
    app.globalData.hold = false;
  },
  // 查看教程
  goCourse() {
    let url = this.data.url;
    let date = this.data.date;
    let title = "房源搬家教程";
    let typename = this.data.typeName;
    wx.navigateTo({
      url:
        "/pages/gatherHouse/playVideo/playVideo?date=" +
        date +
        "&url=" +
        url +
        "&title=" +
        title +
        "&typename=" +
        typename,
    });
  },
  // 将视频连接处理
  CTE(U) {
    let url = U;
    url = url.split("/");
    let pattern = new RegExp("[\u4E00-\u9FA5]+");
    url = url.map((v) => {
      if (pattern.test(v)) {
        v = encodeURIComponent(v);
      }
      return v;
    });
    url = url.join("/");
    return url;
  },
  // 获取所有的视频资源
  queryPmReferenceDetailInfoByRefCode() {
    // let result1;
    return new Promise((resolve, reject) => {
      api.queryPmReferenceDetailInfoByRefCode(
        {
          refCode: "ProductDescription",
        },
        (res) => {
          try {
            let content = res.data.content.map((v) => {
              let refDetailValue = JSON.parse(v.refDetailValue).map((n) => {
                n.url = this.CTE(n.url);
                return n;
              });
              return {
                refDetailName: v.refDetailName,
                refDetailValue: refDetailValue,
              };
            });
            content.map((q) => {
              q.refDetailValue.map((w) => {
                if (w.title == "VR视频采集及分享") {
                  this.setData({
                    date: w.date,
                    typeName: w.typeName,
                    url: w.url,
                  });
                }
              });
            });
            
          } catch (error) {
            
          }
        }
      );
    });
  },
  // 关闭客服引导
  closekefu() {
    if (this.data.subscribe) {
      this.back();
      return;
    }
    this.setData({
      kefu: false,
    });
  },
  // 打开客服引导
  openkefu() {
    this.setData({
      helpGuide: false,
      kefu: true,
      moveHouseFailed: false,
      hold: false,
    });
  },

  // 设置导航栏的高度
  getNavHeight() {
    let systemInfo = wx.getStorageSync("systemInfo");
    this.setData({
      height: systemInfo.height,
      top: systemInfo.top,
    });
  },
  back() {
    console.log('现在可以返回了')
    if (this.data.subscribe) {
      wx.navigateBack({
        delta: 1,
      });
      app.globalData.hold = false;
      return;
    }
    wx.reLaunch({
      url: "/pages/index/index",
    });
    app.globalData.hold = false;
  },
  closeBack() {
    console.log(app.globalData.hold, '挽留操作')
    this.setData({
      back: true,
      hold: app.globalData.hold,
    });
    app.globalData.hold = false;
  },
  // 检验字符串是否含中文
  CheckChinese(val) {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
    return reg.test(val);
  },
  lookHouse() {
    this.closeHelp();
    if (this.data.subscribe) {
      wx.redirectTo({
        url: "/pages/house/RentalHouseDetail/RentalHouseDetail?houdelid=" + this.data.houDelId,
      });
    } else {
      wx.navigateTo({
        url: "/pages/house/RentalHouseDetail/RentalHouseDetail?houdelid=" + this.data.houDelId,
      });
    }
  },
  changeHouStatue(flag) {
    return new Promise((resolve, reject) => {
      api.changeHouStatue(
        {
          delId: this.data.houDelId,
          flag: flag,
        },
        (res) => {
          resolve(res);
        }
      );
    });
  },
  moveOldHouse() {
    this.closeHelp();

    this.handleScanCode(this.data.result, 1);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimer && clearTimer();
    clearTimer = null;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

});
